package com.huashi.dealer.modular.business.category.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huashi.dealer.commonEntity.Category;
import com.huashi.dealer.core.util.TimeUtil;
import com.huashi.dealer.modular.business.category.mapper.CategoryMapper;
import com.huashi.dealer.modular.business.category.param.CategoryListVo;
import com.huashi.dealer.modular.business.category.param.CategoryResponseParam;
import com.huashi.dealer.modular.business.category.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * API分类服务实现类
 * 对应PHP的Category控制器实现
 *
 * @author 谭陈强
 * @since 2025-07-30
 */
@Service("apiCategoryServiceImpl")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public CategoryListVo getCategoryIndex() {
        CategoryListVo responseParam = new CategoryListVo();
        
        // 获取商品分类列表（树状结构）
        List<Category> categoryTree = getCategoryTree(10); // 10对应PHP中的is_type
        
        // 转换为响应格式
        List<CategoryResponseParam.CategoryItem> categoryItems = categoryTree.stream()
                .map(this::convertToCategoryItem)
                .collect(Collectors.toList());
        
        responseParam.setList(categoryItems);
        
        return responseParam;
    }

    @Override
    public CategoryResponseParam getCategoryList(String token, Long parentId) {
        CategoryResponseParam responseParam = new CategoryResponseParam();
        
        // 根据父分类ID获取子分类
        List<Category> categories;
        if (parentId != null) {
            categories = getSubCategories(10, parentId);
        } else {
            categories = getAllCategories(10);
        }
        
        List<CategoryResponseParam.CategoryItem> categoryItems = categories.stream()
                .map(this::convertToCategoryItem)
                .collect(Collectors.toList());
        
        responseParam.setList(categoryItems);
        
        return responseParam;
    }

    @Override
    public CategoryResponseParam getCategoryDetail(Long categoryId, String token) {
        CategoryResponseParam responseParam = new CategoryResponseParam();
        
        // 获取分类详情
        Category category = this.getById(categoryId);
        if (category != null) {
            CategoryResponseParam.CategoryItem categoryItem = convertToCategoryItem(category);
            responseParam.setCategory(categoryItem);
        }
        
        return responseParam;
    }

    @Override
    public CategoryResponseParam getCategoryTree() {
        CategoryResponseParam responseParam = new CategoryResponseParam();
        
        // 获取分类树形结构
        List<Category> categoryTree = getCategoryTree(10);
        
        List<CategoryResponseParam.CategoryItem> categoryItems = categoryTree.stream()
                .map(this::convertToCategoryItem)
                .collect(Collectors.toList());
        
        responseParam.setList(categoryItems);
        
        return responseParam;
    }

    /**
     * 获取分类树
     */
    private List<Category> getCategoryTree(Integer isType) {
        // 获取所有分类
        List<Category> allCategories = getAllCategories(isType);
        
        // 构建树状结构
        return buildCategoryTree(allCategories);
    }

    /**
     * 获取所有分类
     */
    private List<Category> getAllCategories(Integer isType) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_type", isType)
                   .orderByAsc("sort")
                   .orderByAsc("create_time");
        
        return this.list(queryWrapper);
    }

    /**
     * 获取子分类列表
     */
    private List<Category> getSubCategories(Integer isType, Long parentId) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_type", isType)
                   .eq("parent_id", parentId)
                   .eq("is_delete", 0)
                   .orderByAsc("sort")
                   .orderByAsc("create_time");
        
        return this.list(queryWrapper);
    }

    /**
     * 构建分类树
     */
    private List<Category> buildCategoryTree(List<Category> allCategories) {
        // 按父ID分组
        Map<Long, List<Category>> parentMap = allCategories.stream()
                .collect(Collectors.groupingBy(category -> 
                        category.getParentId() != null ? category.getParentId() : 0L));
        
        // 获取顶级分类
        List<Category> rootCategories = parentMap.getOrDefault(0L, new ArrayList<>());
        
        // 递归构建树
        for (Category rootCategory : rootCategories) {
            buildCategoryTreeRecursive(rootCategory, parentMap);
        }
        
        return rootCategories;
    }

    /**
     * 递归构建分类树
     */
    private void buildCategoryTreeRecursive(Category parentCategory, Map<Long, List<Category>> parentMap) {
        List<Category> children = parentMap.get(parentCategory.getCategoryId());
        if (children != null && !children.isEmpty()) {
            // 按排序字段排序
            children.sort(Comparator.comparing(Category::getSort, Comparator.nullsLast(Comparator.naturalOrder())));
            
            // 递归处理子分类
            for (Category child : children) {
                buildCategoryTreeRecursive(child, parentMap);
            }
            
            // 设置子分类
            parentCategory.setChildren(children);
        }
    }

    /**
     * 将Category实体转换为CategoryItem
     */
    private CategoryResponseParam.CategoryItem convertToCategoryItem(Category category) {
        CategoryResponseParam.CategoryItem item = new CategoryResponseParam.CategoryItem();
        item.setCategoryId(category.getCategoryId());
        item.setName(category.getName());
        item.setParentId(category.getParentId());
        item.setSort(category.getSort());
        item.setImageId(category.getImageId());
        item.setWxappId(category.getWxappId());
        item.setIsType(category.getIsType());
        item.setIsGoodsType(category.getIsGoodsType());
        item.setCreateTime(TimeUtil.changeToLocalDateTime(category.getCreateTime()));
        item.setUpdateTime(TimeUtil.changeToLocalDateTime(category.getUpdateTime()));
        
        // 递归转换子分类
        if (category.getChildren() != null && !category.getChildren().isEmpty()) {
            List<CategoryResponseParam.CategoryItem> childItems = category.getChildren().stream()
                    .map(this::convertToCategoryItem)
                    .collect(Collectors.toList());
            item.setChild(childItems);
        }
        
        return item;
    }
} 